import { useRoute } from 'vue-router'
import { useAppStore } from '@/stores/app'

const { body } = document
const WIDTH = 992 // refer to Bootstrap's responsive design

export const useResizeHandler = () => {
  const route = useRoute()
  const appStore = useAppStore()
  watch(
    () => route,
    () => {
      if (appStore.device === 'mobile' && appStore.sidebar.opened) {
        appStore.sidebar.withoutAnimation = false
      }
    },
    {
      deep: true
    }
  )

  onBeforeMount(() => {
    window.addEventListener('resize', _resizeHandler)
  })

  onUnmounted(() => {
    window.removeEventListener('resize', _resizeHandler)
  })

  const _isMobile = () => {
    const rect = body.getBoundingClientRect()
    return rect.width - 1 < WIDTH
  }
  function _resizeHandler() {
    if (!document.hidden) {
      const isMobile = _isMobile()
      appStore.setDevice(isMobile ? 'mobile' : 'desktop')

      if (isMobile) {
        appStore.closeSideBar(true)
      }
    }

    console.log(document.hidden)
  }
}
